package com.huawei.petapp2.activity;

import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.SwitchCompat;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CircleCrop;
import com.bumptech.glide.request.RequestOptions;
import com.huawei.hmf.tasks.OnFailureListener;
import com.huawei.hmf.tasks.OnSuccessListener;
import com.huawei.hmf.tasks.Task;
import com.huawei.hms.support.hwid.HuaweiIdAuthManager;
import com.huawei.hms.support.hwid.request.HuaweiIdAuthParams;
import com.huawei.hms.support.hwid.request.HuaweiIdAuthParamsHelper;
import com.huawei.hms.support.hwid.service.HuaweiIdAuthService;
import com.huawei.petapp2.R;
import com.huawei.petapp2.constant.PushConst;
import com.huawei.petapp2.constant.SPConstants;
import com.huawei.petapp2.service.PushService;
import com.huawei.petapp2.utils.LoginUtil;
import com.huawei.petapp2.utils.PushSPUtil;
import com.huawei.petapp2.utils.SPUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * 设置
 */
public class SettingActivity extends AppCompatActivity {

    private static final String TAG = "SettingActivity";
    // 头像
    private ImageView mIvHeadImg;
    // 昵称
    private TextView mTvNickName;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_setting);
        // 初始化View
        initView();
        // 初始化数据
        initData();
    }

    /**
     * 初始化View
     */
    private void initView() {
        // 顶部返回
        ImageView mIvBack = findViewById(R.id.title_back);
        // 头像
        mIvHeadImg = findViewById(R.id.setting_headimg);
        // 昵称
        mTvNickName = findViewById(R.id.setting_nickName);
        // 消息
        SwitchCompat mSwitchCompat = findViewById(R.id.setting_news);
        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 返回
                finish();
            }
        });
        findViewById(R.id.setting_address).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 地址管理
                Toast.makeText(SettingActivity.this, "待完善", Toast.LENGTH_SHORT).show();
            }
        });
        findViewById(R.id.setting_exit).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 退出登录
                onLoginCheck();
            }
        });
        mSwitchCompat.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                Context context = getApplicationContext();
                PushService.turnOnOff(context, isChecked);
                PushSPUtil.saveConfig(context, PushConst.PUSH_MESSAGE_SWITCH, String.valueOf(isChecked));
            }
        });
    }

    /**
     * 初始化用户信息
     */
    private void initData() {
        String nickName = (String) SPUtil.get(this, SPConstants.KEY_NICK_NAME, "");
        if (TextUtils.isEmpty(nickName)) {
            return;
        }
        // 昵称
        mTvNickName.setText(nickName);

        boolean isHuaweiLogin = (boolean) SPUtil.get(this, SPConstants.KEY_HW_LOGIN, false);
        if (!isHuaweiLogin) {
            return;
        }

        String openId = (String) SPUtil.get(this, SPConstants.KEY_HW_OEPNID, "");
        if (TextUtils.isEmpty(openId)) {
            // 无本地保存的个人信息数据
            return;
        }

        String userInfo = (String) SPUtil.get(this, openId, "");
        if (TextUtils.isEmpty(userInfo)) {
            // 无本地保存的个人信息数据
            return;
        }

        // 头像
        String headPhoto = "";
        try {
            JSONObject jsonObject = new JSONObject(userInfo);
            headPhoto = jsonObject.optString(SPConstants.KEY_HEAD_PHOTO, "");
        } catch (JSONException ignored) {

        }
        if (!TextUtils.isEmpty(headPhoto)) {
            Glide.with(this)
                    .load(headPhoto)
                    .apply(RequestOptions.bitmapTransform(new CircleCrop()))
                    .into(mIvHeadImg);
        }
    }

    /**
     * 登录Check
     */
    private void onLoginCheck() {
        boolean isHuaweiLogin = LoginUtil.isHuaweiLogin(this);
        if (!isHuaweiLogin) {
            onExitLogin();
            return;
        }
        // 退出华为账号
        huaweiSignOut();
    }

    /**
     * 退出
     */
    private void onExitLogin() {
        SPUtil.put(this, SPConstants.KEY_LOGIN, false);
        pushClear();
        finish();
    }

    /**
     * 华为帐号退出登录
     */
    private void huaweiSignOut() {
        HuaweiIdAuthParams authParams = new HuaweiIdAuthParamsHelper(HuaweiIdAuthParams.DEFAULT_AUTH_REQUEST_PARAM).createParams();
        HuaweiIdAuthService authService = HuaweiIdAuthManager.getService(SettingActivity.this, authParams);
        Task<Void> signOutTask = authService.signOut();
        signOutTask.addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "signOut Success");
                // TODO 退出到首页， 不删除华为帐号数据
                SPUtil.put(SettingActivity.this, SPConstants.KEY_HW_LOGIN, false);
                onExitLogin();
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(Exception e) {
                Log.d(TAG, "signOut fail");
                Toast.makeText(SettingActivity.this, "signOut fail", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * push clear
     */
    private void pushClear() {
        Context context = getApplicationContext();
        Map<String, String> topics = PushSPUtil.readTopic(context);
        for (String topic : topics.keySet()) {
            PushService.unsubscribe(context, topic);
        }
        PushSPUtil.clearTopic(context);
        PushSPUtil.clearMessage(context);
        PushSPUtil.saveConfig(context, PushConst.PUSH_MESSAGE_SWITCH, String.valueOf(true));
        PushService.turnOnOff(context, true);
    }

}